Ext.onReady(function() {
	var roleId = Ext.get('roleId').dom.value;
	var root = new Ext.tree.AsyncTreeNode({
		id : '0',
		text: 'root'
	});
	
	var tree = new Ext.tree.TreePanel({
		rootVisible:false,
		region: 'center',
		margins:'3 0 3 3',
        cmargins:'3 3 3 3',
		width:220,
		border : false,
		autoScroll : true, 
		loader: new Ext.tree.TreeLoader({dataUrl: './html/struts/RoleResourceAction_getRoleResources.action', baseParams: {roleId:roleId}}),
		listeners:{
			"checkchange":function(node){
				checkChildren(node, node.attributes.checked);
			}
		},
		
		buttons:[
	        {
	        	text:'保存',
	        	handler: function() {
	        		Ext.MessageBox.confirm('提示', '确定保存?', function(btn) {
	        			if(btn != 'yes') {
							return;
						}
						var selectNodes = getCheckedNodeIds(root);
	        			var allNodes = getAllNodeIds(root);
	        			
		        		Ext.Ajax.request({
							method: 'post',
							url: './html/struts/RoleResourceAction_saveRoleResources.action',
							params: {roleId:roleId,selectNodes: selectNodes, allNodes:allNodes},
						   	success:function(resp){
						    	var obj=Ext.util.JSON.decode(resp.responseText);
						      	if(obj.result == 'success') {
						      		Ext.MessageBox.alert('提示', '保存成功！', function() {
						      			var win = parent.Ext.getCmp('roleResWin');
						      			win.hide();
						      		});
						      	}
						      	else {
						      		Ext.MessageBox.alert('提示', '保存失败！/n' + obj.info);
						      	}
						    }
						});
	        		});
	        	}
	        }
        ]
	});
	tree.setRootNode(root);
	
	function checkChildren(node, checked) {
		node.attributes.checked = checked;
		node.ui.checkbox.checked = checked;
		node.attributes.checked = checked; 

		var childrens = node.childNodes;
		for(var i = 0; i < childrens.length; i++) {
			checkChildren(childrens[i], checked);
		}
	}
	
	function getAllNodeIds(node) {
		var ids = '';
		var childrens = node.childNodes;
		ids += node.id + ',';
			
		for(var i = 0; i < childrens.length; i++) {
			ids += getAllNodeIds(childrens[i]) + ',';
		}
		return ids;
	}
	
	function getCheckedNodeIds(node) {
		var ids = '';
		
		var childrens = node.childNodes;
		if(node.attributes.checked)
			ids += node.id + ',';
			
		for(var i = 0; i < childrens.length; i++) {
			ids += getCheckedNodeIds(childrens[i]) + ',';
		}
		
		return ids;
	}
	
	function getNodeChildrenTexts(node) {
		var text = '';
		if(node.isLeaf()) {
			return node.text;
		}
		else {
			var childrens = node.childNodes;
			for(var i = 0; i < childrens.length; i++) {
				text += getNodeChildrenTexts(childrens[i]) + ',';
			}
		}
		return text;
	}
	
	new Ext.Viewport({
		layout: 'border',
		items:[
			tree
		]
	});
});